package com.lxj.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


/**
 * TestJdbc
 */
public class TestJdbc {

    public static void main(String[] args) {
        Connection c = null;
        Statement s = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            // System.out.println("数据库驱动加载成功");

            c = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/how2java?charactorEncoding=UTF-8", "root", "root");
            // System.out.println("链接成功");

            s = c.createStatement();
            /* 添加 */
            // for (int i = 1; i <= 100; i++) {
                // String sql = "insert into user (`user_name`, `password`) values ('jiaoxiliang','jiao123')";    // 添加
                // extracted(s, sql);
            // }
            /* 删除 */
            // String sql = "delete from article where id = 5";
            // s.execute(sql);
            /* 更改 */
            // extracted(s, sql);

            /* 查询 */
            String user_name = "jiaoxiliang";
            String password = "jiao1623";
            String sql = "select * from user where user_name = '"+user_name+"' and password = '"+password+"' limit 1";
            ResultSet rs = s.executeQuery(sql);
            if(rs.next()) {
                System.out.println("账号输入正确");
            } else {
                System.out.println("账号错误");
            }
            // while (rs.next()) {
            //     int id = rs.getInt("id");
            //     String user_name = rs.getString("user_name");
            //     String password = rs.getString("password");

            //     System.out.printf("%d\t%s\t%s%n", id, user_name, password);
            // }

            // System.out.println("执行sql成功");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (s != null) {
                try {
                    s.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (c != null) {
                try {
                    c.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

        System.exit(0);
    }

    private static void extracted(Statement s, String sql) throws SQLException {
        s.execute(sql);
    }
}